package com.example.lenovo.manager;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.SaveCallback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import java.util.Locale;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;


import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


@SuppressLint("SdCardPath")
public class Product extends Fragment {

    private EditText Name,PriceYuan,PriceJiao,Declear;
    private Button Commit,Image;
    private TextView Error;
    File photoFile = null;
    private ImageView mImageView;
    String PhotoPath;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_product, container, false);

        Name = (EditText) view.findViewById(R.id.ProductName);
        PriceYuan = (EditText) view.findViewById(R.id.ProductPriceYuan);
        PriceJiao = (EditText) view.findViewById(R.id.ProductPriceJiao);
        Declear = (EditText) view.findViewById(R.id.ProductDeclear);
        Commit = (Button) view.findViewById(R.id.Commit);
        Error = (TextView) view.findViewById(R.id.ErrorPrint);
        Image = (Button) view.findViewById(R.id.ProductImg);
        mImageView = (ImageView) view.findViewById(R.id.ImagePhoto);

        /*Image.setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, 1);
                    }
                }
        );*/

        Image.setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 跳转至拍照界面
                        Intent intentPhote = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intentPhote.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        File out = new File(getPhotopath());
                        Uri uri = Uri.fromFile(out);
                        // 获取拍照后未压缩的原图片，并保存在uri路径中
                        intentPhote.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//                intentPhote.putExtra(MediaStore.Images.Media.ORIENTATION, 180);
                        startActivityForResult(intentPhote, 2000);
                    }
                }
        );

        Commit.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (CheckProduct()) {
                            CommitProduct();
                        }
                    }
                }
        );
        return view;
    }

    /**
     * 获取图片信息
     * @param requestCode
     * @param resultCode
     * @param data
     *//*
    @SuppressLint("SdCardPath")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            String sdStatus = Environment.getExternalStorageState();
            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                Log.i("TestFile",
                        "SD card is not avaiable/writeable right now.");
                return;
            }
            new DateFormat();
            String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            Toast.makeText(getActivity(), name, Toast.LENGTH_LONG).show();
            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式

            FileOutputStream b = null;
            File file = new File("/sdcard/Image/");
            file.mkdirs();// 创建文件夹
            String fileName = "/sdcard/Image/"+name;

            try {
                b = new FileOutputStream(fileName);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                Log.d("bitmap:compress", "图片大小:" + b);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    b.flush();
                    b.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try
            {
                mImageView.setImageBitmap(bitmap);// 将图片显示在ImageView里
                final AVFile upload = AVFile.withAbsoluteLocalPath("Product.jpg", fileName);
                upload.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(AVException e) {
                        PhotoPath = upload.getUrl();
                    }
                });
            }catch(Exception e)
            {
                Log.e("error", e.getMessage());
            }

        }
    }*/



    /**
     * 添加成功对话框
     */
    private void dialog1(){
        AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
        builder.setTitle("操作信息");
        builder.setMessage("添加产品成功！");
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setPositiveButton("返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog
            }
        });
        builder.create().show();
    }

    /**
     * 检查产品信息函数
     * @return
     */
    private boolean CheckProduct(){
        if(Name.getText().toString().length() == 0){
            Error.setText("产品名称必有");
            return false;
        }
        if(PriceYuan.getText().toString().length() == 0){
            Error.setText("价格信息不完整！");
            return false;
        }
        if(PriceJiao.getText().toString().length() == 0){
            Error.setText("价格信息不完整！");
        }
        if(Declear.getText().toString().length() == 0){
            Error.setText("产品简介必有");
            return false;
        }
        return true;
    }

    /**
     * 提交产品信息函数
     */
    private void CommitProduct(){
        AVOSCloud.initialize(getActivity(), "Po6OudEc9QxRgv1qcussxBxi-gzGzoHsz", "EFNsW7y5aXtKMkpU50xyhHNk");
        AVObject todoFolder = new AVObject("ProductInfo");// 构建对象
        todoFolder.put("productname", Name.getText().toString());
        todoFolder.put("productprice", PriceYuan.getText().toString()+"."+PriceJiao.getText().toString()+"0");
        System.out.println("&&&&&&&&&&&&&&&&&&&" + PhotoPath);
        todoFolder.put("productImage", PhotoPath);
        todoFolder.put("productdeclear", Declear.getText().toString());
        todoFolder.saveInBackground();// 保存到服务端
        dialog1();
    }









    /**
     * 获取原图片存储路径
     * @return
     */
    private String getPhotopath() {
        // 照片全路径
        String fileName = "";
        // 文件夹路径
        String pathUrl = Environment.getExternalStorageDirectory()+"/mymy/";
        String imageName = "imageTest.jpg";
        File file = new File(pathUrl);
        file.mkdirs();// 创建文件夹
        fileName = pathUrl + imageName;
        PhotoPath = fileName;
        return fileName;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 2000 && resultCode == Activity.RESULT_OK) {
            Bitmap bitmap = getBitmapFromUrl(getPhotopath(), 313.5, 462.0);
            saveScalePhoto(bitmap);
            mImageView.setImageBitmap(bitmap);
        }
    }
    /**
     * 根据路径获取图片资源（已缩放）
     * @param url 图片存储路径
     * @param width 缩放的宽度
     * @param height 缩放的高度
     * @return
     */
    private Bitmap getBitmapFromUrl(String url, double width, double height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 设置了此属性一定要记得将值设置为false
        Bitmap bitmap = BitmapFactory.decodeFile(url);
        // 防止OOM发生
        options.inJustDecodeBounds = false;
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = 1;
        float scaleHeight = 1;
//        try {
//            ExifInterface exif = new ExifInterface(url);
//            String model = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // 按照固定宽高进行缩放
        // 这里希望知道照片是横屏拍摄还是竖屏拍摄
        // 因为两种方式宽高不同，缩放效果就会不同
        // 这里用了比较笨的方式
        if(mWidth <= mHeight) {
            scaleWidth = (float) (width/mWidth);
            scaleHeight = (float) (height/mHeight);
        } else {
            scaleWidth = (float) (height/mWidth);
            scaleHeight = (float) (width/mHeight);
        }
//        matrix.postRotate(90); /* 翻转90度 */
        // 按照固定大小对图片进行缩放
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
        // 用完了记得回收
        bitmap.recycle();
        return newBitmap;
    }

    /**
     * 存储缩放的图片
     * @param data 图片数据
     */
    private void saveScalePhoto(Bitmap bitmap) {
        // 照片全路径
        String fileName = "";
        // 文件夹路径
        String pathUrl = Environment.getExternalStorageDirectory().getPath()+"/mymy/";
        String imageName = "imageScale.jpg";
        FileOutputStream fos = null;
        File file = new File(pathUrl);
        file.mkdirs();// 创建文件夹
        fileName = pathUrl + imageName;
        try {
            fos = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            final AVFile upload = AVFile.withAbsoluteLocalPath("Product.jpg", fileName);
            upload.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    PhotoPath = upload.getUrl();
                }
            });

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
